package com.coder.oj.system.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.coder.oj.common.core.R;
import com.coder.oj.common.entity.User;
import com.coder.oj.common.enums.CommonStatusEnum;
import com.coder.oj.common.exception.DataException;
import com.coder.oj.common.mapper.UserMapper;
import com.coder.oj.common.service.RedisService;
import com.coder.oj.common.utils.JwtUtil;
import com.coder.oj.system.mapstruct.UserMapstruct;
import com.coder.oj.system.vo.CallBackVo;
import com.coder.oj.system.vo.InfoVo;
import com.coder.oj.system.vo.LoginVo;
import com.coder.oj.system.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URISyntaxException;

@Api(tags = {"登录接口"})
@RestController
@RequestMapping("/login")
public class LoginController {

    @Value("${login.check-key}")
    private String checkKey;

    @Value("${login.url}")
    private String loginUrl;

    @Value("${login.secret-key}")
    private String loginSecretKey;

    @Autowired
    private RedisService redisService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserMapstruct userMapstruct;

    @GetMapping("/info")
    @ApiOperation("获取二维码")
    public R<InfoVo> info() throws URISyntaxException, IOException {
        HttpClient httpClient = HttpClients.createDefault();
        URIBuilder uriBuilder = new URIBuilder(loginUrl);
        uriBuilder.addParameter("secretKey", loginSecretKey);
        HttpGet get = new HttpGet(uriBuilder.build());
        HttpResponse response = httpClient.execute(get);
        JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
        return R.ok().setResult(jsonObject.get("data"));
    }

    @PostMapping("/callback")
    @ApiOperation("登录回调")
    public CallBackVo callback(
            @RequestParam(value = "userId", required = false) String openId,
            @RequestParam(value = "avatar", required = false) String avatar,
            @RequestParam(value = "nickname", required = false) String nickname,
            @RequestParam(value = "tempUserId", required = false) String tempUserId
    ) {
        User user = userMapper.getUserByOpenId(openId);
        if(ObjectUtils.isEmpty(user)) {
            // 第一次登录，新增用户
            User newUser = new User();
            newUser.setOpenId(openId);
            newUser.setAvatar(avatar);
            newUser.setNickname(nickname);
            userMapper.insert(newUser);
        } else {
            if(CommonStatusEnum.getEnum(user.getStatus()) == CommonStatusEnum.DISABLED) {
                return null;
            }
            // 更新用户信息
            user.setAvatar(avatar);
            user.setNickname(nickname);
            userMapper.updateById(user);
        }
        Long userId = userMapper.getIdByOpenId(openId);
        LoginVo vo = new LoginVo();
        vo.setToken(JwtUtil.sign(userId));
        vo.setUserInfo(userMapstruct.toVO(userMapper.selectById(userId)));
        // 将用户信息放入登录池中
        redisService.set(tempUserId, vo, JwtUtil.EXPIRE_TIME / 1000);
        return new CallBackVo();
    }

    @GetMapping("/check")
    @ApiOperation("登录检查")
    public R<LoginVo> check(@RequestParam("tempId") String tempId) {
        if(!redisService.hasKey(tempId)) {
            throw new DataException(200, "用户尚未登录");
        }
        return R.ok().setResult(redisService.get(tempId));
    }
}
